<template>
  <div class="swiper-container" ref="mySwiperRef" id="mySwiper">
    <slot>
      <div class="swiper-wrapper">
        <div
          class="swiper-slide"
          v-for="(banner, index) in list"
          :key="banner.id"
        >
          <img :src="banner.imgUrl" />
        </div>
      </div>
      <!-- 如果需要分页器 -->
      <div class="swiper-pagination"></div>

      <!-- 如果需要导航按钮 -->
      <div class="swiper-button-prev"></div>
      <div class="swiper-button-next"></div>
    </slot>
  </div>
</template>

<script>
import Swiper from "swiper/swiper-bundle.min.js";
import "swiper/swiper-bundle.min.css";
export default {
  name: "SwiperList",
  props: {
    list: {
      type: Array,
      required: true,
    },
    options: {
      type: Object,
      default() {
        return {
          autoplay: {
            disableOnInteraction: false,
          },
          loop: true, // 循环模式选项

          // 如果需要分页器
          pagination: {
            el: ".swiper-pagination",
          },

          // 如果需要前进后退按钮
          navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
          },
        };
      },
    },
  },
  data() {
    return {
      mySwiper: null,
    };
  },
  watch: {
    list: {
      handler(nval) {
        if (nval && nval.length) {
          //vue中dom更新是异步，数据回来，dom才更新
          //dom更新完，再执行代码
          // $nextTick 传入一个回调，回调内容在dom更新完之后立即执行
          this.$nextTick(() => {
            this.initSwiper();
          });
        }
      },
      immediate: true,
    },
  },
  methods: {
    initSwiper() {
      // this.mySwiper = new Swiper('.swiper-container', this.options)
      this.mySwiper = new Swiper(this.$refs.mySwiperRef, this.options);
    },
  },
};
</script>

<style scoped></style>
